'''
背诵作用域的概念
    程序创建, 访问, 改变一个变量时, 都是在一个保存该变量的空间内进行, 这个空间被称为命名空间, 即作用域
练习作用域之间的转换

默写一个装饰器, 用来输出函数的执行时间.

使用装饰器来为斐波那契函数添加缓存

def cache_deco(func):
	# 保存n执行后的结果
	a = {}
	# 判断当前cache a中是否有结果, 有的话就直接返回, 没有就执行以下
	result = func(n)
	return result

@cache_deco
def fibo(n):
	pass
'''
# 练习作用域之间的转换
'''
a = 1
def foo():
    global a
    a = 2
    print(a)
foo()
print(a)
'''
a = 1
b = 7
def foo(a,b):
    c = a
    a = b
    b = c
    print("函数内的a：" ,a, "，b：", b)
    return a,b
print("函数外的a：" ,a, "，b：", b)
print(foo(a,b))
def func():
    total = 0
    count = 0
    def refoo(a,b):
        nonlocal total,count
        print("开始total为：", total, "count为：", count)
        total += a
        count += b
        print("现在total为：",total,"count为：",count)
        return refoo
    refoo(1,1)
    print(total,count)
func()

# 默写一个装饰器, 用来输出函数的执行时间.
import time
def clock_it_deco(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"{func.__name__} execute time: {format(end_time - start_time, '.2f')} s")
        return result
    return wrapper

# @other_deco
@clock_it_deco
def foo_1(a, b):
    count = 1
    while True:
        if count > a ** b:
            break
        count += 1

foo_1(10, 5)

# 使用装饰器来为斐波那契函数添加缓存
a = {}
def cache_deco(func):
    global a
    def infun(n):
        if n not in a:
            a[n] = func(n)
        return a[n]
    return infun


@cache_deco
def fibo(n):
    if n < 2:
        return n
    else:
        return fibo(n - 2) + fibo(n - 1)
print(fibo(10))
print(a)